import { WritableComputedRef, getCurrentInstance, computed } from "vue";

export default function useVModel<T>(
  props: Readonly<Record<string, any>>,
  key = "modelValue",
  defaultValue?: T,
  emit?: (name: string, ...args: unknown[]) => void
): WritableComputedRef<T | undefined> {
  const instance = getCurrentInstance();
  const _emit = emit || instance?.emit;
  return computed<T | undefined>({
    get() {
      return (props[key] as T) || defaultValue;
    },
    set(value) {
      _emit && _emit(`update:${key}`, value);
    },
  });
}
